#include <iostream>
using namespace std;
#include <unistd.h>
#include "stdTcpService.h"
#include "threadPool.h"

#define PORT 8888
#define SIZE 32
#include <json-c/json.h>
#include "messageHandle.h"
void *thread_func(void *arg)
{
    // pthread_detach(pthread_self());
    StdTcpSocket *clientSocket = (StdTcpSocket *)arg;
    std::string data;
    int readBytes = 0;
    while (1)
    {
        // 清空数据
        data.clear();   
        // 接收客户端信息
        readBytes = clientSocket->recvMessage(data);
        if (readBytes < 0)
        {
            break;
        }
        else if (readBytes == 0)
        {
            cout << "客户端下线" << endl;
            break;
        }
        else
        {
            MessageHandle message(*clientSocket);
            message.handleMessage(data);
        }
    }
    return NULL;
}

int main()
{
    // 创建线程池
    ThreadPool pool(3, 6, 10);
    StdTcpServer server;
    // 设置监听
    server.setListen(PORT);
    std::cout << "等待客户端连接" << endl;
    int ret = 0;
    while (1)
    {
        StdTcpSocket *clientSocket = server.getClientSocket();
        // 程序到这个地方,意味着有新的连接了
        pool.addTask(thread_func, clientSocket);

#if 0
        pthread_t tid;
        pthread_create(&tid, NULL, thread_func, clientSocket);
#endif

        sleep(1);
        // std::string data;
        // // 接收客户端信息
        // clientSocket->recvMessage(data);

        // cout << "data:" << data << endl;

        // 是否在这里释放资源解决文件描述符无法重用的问题
        // delete clientSocket;
    }
    return 0;
}